from flask import render_template, g, jsonify, request, current_app, session, abort

from info import db, constants
from info.models import News, Category, User
from info.modules.profile import profile_blue
from info.utils.image_storage import storage
from info.utils.common import user_is_login
from info.utils.response_code import RET


@profile_blue.route('/info')
@user_is_login
def get_profile_data():
    """个人中心"""
    user = g.user
    if not user:
        return jsonify(errno=RET.USERERR, errmsg="用户未登录")
    data = {
        'user_info': user.to_dict()
    }
    return render_template('news/user.html', data=data)


@profile_blue.route('/user_base_data', methods=['get', 'POST'])
@user_is_login
def user_base_data():
    """用户基础内容"""
    user = g.user
    if request.method == "GET":
        return render_template('news/user_base_info.html', data={'user_info': user.to_dict()})

    else:
        params = request.json
        gender = params.get('gender')
        signature = params.get('signature')
        nick_name = params.get('nick_name')

        if not all([gender, signature, nick_name]):
            return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
        if gender not in ['man', 'woman']:
            return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

        user.nick_name = nick_name
        user.gender = gender
        user.signature = signature

        try:
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            db.session.rollback()
            return jsonify(errno=RET.DBERR, errmsg="数据库保存错误")
        session['user_name'] = nick_name
        return jsonify(errno=RET.OK, errmsg="基本信息修改成功")


@profile_blue.route('/user_pic_data', methods=['GET', 'POST'])
@user_is_login
def user_pic_data():
    """用户修改图片"""
    user = g.user
    if request.method == "GET":
        return render_template('news/user_pic_info.html', data={'user_info': user.to_dict()})

    #  暂且没有七牛云账号，所以这里后面再完善
    # 获取图片
    try:
        act_image = request.files.get('avatar').read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="读取文件错误")
    # 存储图片
    try:
        image_key = storage(act_image)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="第三方错误")
    user.avatar_url = image_key
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="数据库存储错误")
    return jsonify(errno=RET.OK, errmsg="存储图片成功",
                   data={"avatar_url": constants.QINIU_DOMIN_PREFIX + image_key})


@profile_blue.route('/user_password_change', methods=['get', 'post'])
@user_is_login
def user_password_change():
    """
    修改密码：

    :return:
    """
    if request.method == "GET":
        return render_template("news/user_pass_info.html")
    # 获取参数
    params = request.json
    old_password = params.get('old_password')
    new_password = params.get('new_password')

    if not all([old_password, new_password]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    user = g.user

    result = user.check_password(old_password)
    if not result:
        return jsonify(errno=RET.PWDERR, errmsg="原始密码错误")

    user.password = new_password

    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="数据库插入错误")
    return jsonify(errno=RET.OK, errmsg="修改密码成功")


@profile_blue.route('/user_collection')
@user_is_login
def user_collection():
    """用户的收藏"""
    page = request.args.get("page", 1)

    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    user = g.user
    collection_data = []
    current_page = 1
    total_page = 1

    try:
        # 查询用户收藏的新闻
        paginate = user.collection_news.paginate(page, constants.USER_COLLECTION_MAX_NEWS, False)
        current_page = paginate.page
        total_page = paginate.pages
        collection_data = paginate.items
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库查询错误")

    collection_dict_list = []
    for collection in collection_data:
        collection_dict_list.append(collection.to_basic_dict())
    data = {
        "collections": collection_dict_list,
        "current_page": current_page,
        "total_page": total_page
    }
    return render_template("news/user_collection.html", data=data)


@profile_blue.route('/user_release_news', methods=['GET', 'POST'])
@user_is_login
def user_release_news():
    """
    发布新闻
    :return:
    """
    if request.method == "GET":

        category = []
        try:
            category = Category.query.filter().all()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg="数据库查询错误")
        category_dict_list = []
        for c in category:
            # 获取字典
            cate_dict = c.to_dict()
            # 拼接内容
            category_dict_list.append(cate_dict)
        category_dict_list.pop(0)
        return render_template('news/user_news_release.html', data={"categories": category_dict_list})

    # 1. 获取要提交的数据
    title = request.form.get("title")
    source = "个人发布"
    digest = request.form.get("digest")
    content = request.form.get("content")
    # index_image = request.files.get("index_image")
    category_id = request.form.get("category_id")

    # 1.1 判断数据是否有值
    if not all([title, source, digest, content, category_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    # 获取图片
    try:
        act_image = request.files.get('index_image').read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="读取文件错误")
    # 存储图片
    try:
        image_key = storage(act_image)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="第三方错误")

    new = News()
    # 新闻标题
    new.title = title
    # 新闻的内容
    new.content = content
    # 新闻的来源
    new.source = source
    # 新闻摘要
    new.digest = digest
    # 新闻的分类
    new.category_id = category_id
    # 新闻的图片
    new.index_image_url = constants.QINIU_DOMIN_PREFIX + image_key
    #
    new.user_id = g.user.id
    # 新闻的状态，1代表待审核，0 代表审核通过
    new.status = 1

    try:
        db.session.add(new)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="新闻发布失败")
    return jsonify(errno=RET.OK, errmsg="新闻发布成功")


@profile_blue.route('/user_list_data')
@user_is_login
def user_list_data():
    """用户新闻列表"""
    page = request.args.get("page", 1)

    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1
    user = g.user
    user_release = []
    current_page = 1
    total_page = 1
    try:
        paginate = News.query.filter(News.user_id == user.id).paginate(page, constants.USER_COLLECTION_MAX_NEWS, False)
        user_release = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库查询错误")
    news_dict_li = []
    for user_news in user_release:
        news_dict_li.append(user_news.to_review_dict())
        print (user_news.to_review_dict()['status'])
    data = {
        'news_list': news_dict_li,
        "total_page": total_page,
        "current_page": current_page
    }

    return render_template('news/user_news_list.html', data=data)


@profile_blue.route('/user_follow')
@user_is_login
def user_follow():
    # 获取页数
    p = request.args.get("p", 1)
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1

    user = g.user

    follows = []
    current_page = 1
    total_page = 1
    try:
        paginate = user.followed.paginate(p, constants.USER_FOLLOWED_MAX_COUNT, False)
        # 获取当前页数据
        follows = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    user_dict_li = []

    for follow_user in follows:
        user_dict_li.append(follow_user.to_dict())
    data = {"users": user_dict_li, "total_page": total_page, "current_page": current_page}
    return render_template('news/user_follow.html', data=data)

@profile_blue.route('/other_info')
@user_is_login
def other_info():
    """查看其他用户信息"""
    user = g.user

    # 获取其他用户id
    user_id = request.args.get("id")
    if not user_id:
        abort(404)
    # 查询用户模型
    other = None
    try:
        other = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
    if not other:
        abort(404)

    # 判断当前登录用户是否关注过该用户
    is_followed = False
    if g.user:
        if other.followers.filter(User.id == user.id).count() > 0:
            is_followed = True

    # 组织数据，并返回
    data = {
        "user_info": user.to_dict(),
        "other_info": other.to_dict(),
        "is_followed": is_followed
    }
    return render_template('news/other.html', data=data)

@profile_blue.route('/other_news_list')
def other_news_list():
    # 获取页数
    p = request.args.get("p", 1)
    user_id = request.args.get("user_id")
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    if not all([p, user_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    try:
        user = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询错误")

    if not user:
        return jsonify(errno=RET.NODATA, errmsg="用户不存在")
    total_page = 1
    current_page =1
    try:
        paginate = News.query.filter(News.user_id == user.id).paginate(p, constants.OTHER_NEWS_PAGE_MAX_COUNT, False)
        # 获取当前页数据
        news_li = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询错误")

    news_dict_li = []

    for news_item in news_li:
        news_dict_li.append(news_item.to_review_dict())
    data = {"news_list": news_dict_li, "total_page": total_page, "current_page": current_page}
    return jsonify(errno=RET.OK, errmsg="OK", data=data)
